package com.graduation.log.service.impl;

import java.time.LocalDate;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.client.StudentClint;
import com.graduation.client.WorkClient;
import com.graduation.log.mapper.InternshipLogMapper;
import com.graduation.log.service.InternshipLogService;
import com.graduation.model.entity.*;
import com.graduation.model.enu.LogEnum;
import com.graduation.model.vo.DictEeVo;
import com.graduation.model.vo.GradeQueryVo;
import com.graduation.model.vo.LogExVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianwenle
 * @since 2022-11-18
 */
@Service
public class InternshipLogServiceImpl extends ServiceImpl<InternshipLogMapper, InternshipLog> implements InternshipLogService {

    @Autowired
    private StudentClint studentClint;

    @Autowired
    private WorkClient workClient;

    @Override
    public Map<String, Object> pageList(Integer pageNum, Integer pageSize, GradeQueryVo gradeQueryVo) {

        Page<InternshipLog> page = new Page<>(pageNum, pageSize);
        QueryWrapper<InternshipLog> wrapper = new QueryWrapper<>();

        if (gradeQueryVo.getTeacherId() != null) {
            wrapper.eq("teacher_id", gradeQueryVo.getTeacherId());
        }

        if (gradeQueryVo.getStudentId() != null) {
            wrapper.eq("student_id", gradeQueryVo.getStudentId());
        }

        if (gradeQueryVo.getStatus() != null) {
            wrapper.eq("status", gradeQueryVo.getStatus());
        }

        baseMapper.selectPage(page, wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        List<InternshipLog> internshipLogs = page.getRecords();
        for (InternshipLog internshipLog : internshipLogs) {
            this.packageLogs(internshipLog);
        }
        map.put("list", internshipLogs);
        return map;
    }

    @Override
    public void upload(Student student) {
        // 判断日志是否存在 存在就更新状态为未查看 不存在就插入
        QueryWrapper<InternshipLog> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id", student.getId());
        wrapper.eq("teacher_id", student.getTeacherId());
        InternshipLog log1 = baseMapper.selectOne(wrapper);
        if (log1 != null) {
            log1.setStatus(LogEnum.MARKING_NO.getStatus());
            baseMapper.updateById(log1);
        } else {
            InternshipLog log = new InternshipLog();
            log.setStudentId(student.getId());
            log.setTeacherId(student.getTeacherId());
            log.setFileName(student.getFileName());
            log.setFileUrl(student.getFileUrl());
            baseMapper.insert(log);
        }


    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("学生实习日志信息汇总", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 遍历当前已完成提交实习日志的学生
            // 遍历实习日志 获取学生的id
            List<InternshipLog> internshipLogs = baseMapper.selectList(null);

            ArrayList<LogExVo> list = new ArrayList<>();

            for (InternshipLog internshipLog : internshipLogs) {


                // 获取学生编号
                Long studentId = internshipLog.getStudentId();
                // 获取学生的信息

                Student student = studentClint.getFullStudentInfoById(studentId);

                // 获取指导老师编号
                Long teacherId = internshipLog.getTeacherId();

                // 获取指导老师的信息
                Teacher teacherInfo = studentClint.getTeacherInfoByTeacherId(teacherId);

                // 获取学生的工作信息
                WorkInfo studentWorkInfo = workClient.getStudentWorkInfo(studentId);

                if (studentWorkInfo != null) {
                    // 获取企业的信息
                    String enterpriseCode = studentWorkInfo.getEnterpriseCode();
                    Enterprise enterprise = workClient.getEnterpriseInfoByCode(enterpriseCode);

                    // 填充数据
                    LogExVo logExVo = new LogExVo();
                    logExVo.setLoginNo(student.getLoginNo());
                    logExVo.setUsername(student.getUsername());
                    logExVo.setPhone(student.getPhone());
                    logExVo.setFullInfo(student.getFullInfo());
                    logExVo.setWorkStatus(student.getWorkStatus() == 0 ? "是" : "否");
                    logExVo.setWorkCode(studentWorkInfo.getWorkCode());
                    logExVo.setWorkStartTime(studentWorkInfo.getWorkStartTime().toString());
                    logExVo.setWorkEndTime(studentWorkInfo.getWorkEndTime().toString());
                    logExVo.setTeacherName(teacherInfo.getUsername());
                    logExVo.setTeacherPhone(teacherInfo.getPhone());
                    logExVo.setTeacherEmail(teacherInfo.getEmail());
                    logExVo.setName(enterprise.getName());
                    logExVo.setOrgtype(enterprise.getOrgtype());
                    logExVo.setCode(enterprise.getCode());
                    logExVo.setMemo(enterprise.getMemo());

                    list.add(logExVo);
                }

            }

            EasyExcel.write(response.getOutputStream(), LogExVo.class).sheet("学生实习日志").doWrite(list);


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        List<Dict> dicts = baseMapper.selectList(null);
//        List<DictEeVo> eeVos = new ArrayList<>();
//        for (Dict dict : dicts) {
//            DictEeVo dictEeVo = new DictEeVo();
//            BeanUtils.copyProperties(dict, dictEeVo);
//            eeVos.add(dictEeVo);
//        }
//        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(eeVos);

    }


    private void packageLogs(InternshipLog internshipLog) {
        Student student = studentClint.getStudent(internshipLog.getStudentId());
        internshipLog.setStudentName(student.getUsername());
        internshipLog.setStatusString(LogEnum.getValueByStatus(internshipLog.getStatus()));
    }
}
